package com.appspot.yozmcup.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

import oauth.signpost.OAuthConsumer;

public class Request {
	private final static Logger log = Logger.getLogger(Request.class.getName());
	OAuthConsumer consumer;
	HttpURLConnection req;
	public Request(){ }
	
	public Request(OAuthConsumer consumer){
		this.consumer = consumer;
	}
	
	public String getResult(String urlStr) throws Exception{
		HttpURLConnection req = getRequest(urlStr);
		if( req.getResponseCode() == 200) {
			return convertinputStreamToString(req.getInputStream());
		}
		return "exception";
	}
	
	private HttpURLConnection getRequest(String urlStr) throws Exception{
		URL url = new URL(urlStr);
		HttpURLConnection req = (HttpURLConnection) url.openConnection();
		if(consumer != null){
			consumer.sign(req);
		}
		req.connect();
		return req;
	}
	
	public String convertinputStreamToString(InputStream ists) throws IOException {
        if (ists != null) {
            StringBuilder sb = new StringBuilder();
            String line;
 
            try {
                BufferedReader r1 = new BufferedReader(new InputStreamReader(ists, "UTF-8"));
                while ((line = r1.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                ists.close();
            }
            return sb.toString();
        } else {       
            return "";
        }
    }
}
